<template>
  <div class="login">
    <van-nav-bar title="登录" />
    <van-form ref="loginForm" @submit="login">
      <van-field
        placeholder="请输入手机号码"
        name="mobile"
        v-model.trim="user.mobile"
        :rules="formRules.mobile"
      >
        <template #left-icon>
          <i class="toutiao toutiao-shouji" />
        </template>
      </van-field>
      <van-field placeholder="请输入密码" v-model="user.code" :rules="formRules.code">
        <i class="toutiao toutiao-yanzhengma" slot="left-icon" />
        <template #button>
          <van-count-down
            v-if="sending"
            @finish="finishFn"
            :time="time"
            format="ss 秒"
          />
          <van-button
            v-else
            round
            type="default"
            size="small"
            @click="sendCode"
            native-type="button"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn">
        <van-button block type="info" native-type="submit" :loading="loading"> 登录 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { sendSms, login } from '@/api/user'

export default {
  name: 'Login',
  data () {
    return {
      user: {
        mobile: '',
        code: ''
      },
      formRules: {
        mobile: [
          { required: true, message: '手机号码不能为空' },
          { pattern: /^1\d{10}$/, message: '手机号码不正确' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          { pattern: /^\d{4,6}$/, message: '验证码为4-6位数字' }
        ]
      },
      time: 60000,
      sending: false,
      loading: false
    }
  },
  methods: {
    // 发送验证码方法
    async sendCode () {
      // 1. 对手机号码进行校验，如果校验不通过，则不进行任何处理
      await this.$refs.loginForm.validate('mobile')
      // 2. 校验通过利用手机号码调用发送验证码的接口
     await sendSms(this.user.mobile)
      this.$toast.success('短信验证码发送成功')
      this.sending = true
    },
    // 处理倒计时结束的方法
    finishFn () {
      // 5. 倒计时结束，恢复发送验证码按钮
      this.sending = false
      this.time = 60000
    },
    // 登录的方法
    async login () {
      // 1. 利用表单信息调用登录接口，拿到token
      try {
        this.loading = true
        const res = await login(this.user)
        this.$toast.success('登录成功')
        // 2. 把token存储起来（暂时存储到LocalStorage中）
        this.$store.commit('setUser',res.data)
        // 3. 跳转到首页
        this.$router.push('/')
      } 
       finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.login-btn {
  margin: 16px;
}
</style>